package com.qiaodata.datatrans.web;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.qiaodata.datatrans.utils.HttpRequest;
import com.qiaodata.datatrans.utils.JsonResult;
import com.qiaodata.datatrans.utils.ReadTxtUtil;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/6 0006.
 */
@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

//    @RequestMapping("/test")
//    public Object test() {
//
//        String url = "http://10.18.99.182:8080/importdata?filepath=/root/500238053.txt";
//        String forObject = restTemplate.getForObject(url, String.class);
//        JSONObject jsonObject = JSONObject.parseObject(forObject);
//        if (jsonObject==null) {
//
//        }else {
//            String result = (String)jsonObject.get("result");
//        }
//
//        return forObject;
//    }

    @RequestMapping("/readfilepath")
    public Object testReadFilePath(@RequestParam("filepath") String filepath) {
        if (filepath==null || "".equals(filepath.trim())) {
            return JsonResult.getInstance("0");
        }

        List<String> resumes = ReadTxtUtil.readTxtFile(filepath);//按行读取txt文档
        String jsonstr = resumes.get(0);
        String url = "http://10.18.99.182:8080/importdata";
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        JSONObject jsonstr1 = JSONObject.parseObject(jsonstr);
        String requestJson = jsonstr1.toJSONString();
        HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
        Object result = restTemplate.postForObject(url, entity, Object.class);
        System.out.println(result);

        return result;
    }

    @RequestMapping("/filespath")
    public Object test10wFiles(@RequestParam("filespath") String filespath) {
        File file = new File(filespath);
//        String strTxt = path + "//error.txt";
        //记录错误的信息
//        FileWriter fw1 = new FileWriter(strTxt);//本地模式存储
        if (file.exists()) {
            LinkedList<File> list = new LinkedList<File>();
            File[] files = file.listFiles();// 该文件目录下文件全部放入数组
            for (File file2 : files) {
                String fileName = file2.getName();
                if (file2.isDirectory()) {
                    System.out.println("文件夹:" + file2.getAbsolutePath());
                    list.add(file2);
                } else if (fileName.endsWith("txt")){
                    System.out.println("文件:" + file2.getAbsolutePath());
                    //拿到文件
                    String filePath =file2.getAbsolutePath();
                    List<String> resumes = ReadTxtUtil.readTxtFile(filePath);//按行读取txt文档
                    try {
                        //处理文件数据(一个文件一条)
                        String jsonstr = resumes.get(0);
//                        String url = "http://10.18.99.182:8080/importdata";
                        String url = "http://localhost:8080/importdata?filepath=D:\\data\\resource";
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        JSONObject jsonstr1 = JSONObject.parseObject(jsonstr);
                        String requestJson = jsonstr1.toJSONString();
                        HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
                        Object result = restTemplate.postForObject(url, entity, Object.class);
                        Map res = (Map) result;
                        System.out.println(res.toString());
                    } catch (Exception e) {
                        continue;
                    }

                } else {
                    continue;
                }
            }
            return "=============end============";
            //处理数据
//			String s = qzAreaList.get(dicNumber);
//			String s1 = qdAreaList.get(s);
//			return s1;

        } else {
            System.out.println("文件不存在!");
//			return null;
        }
        return "文件夹不存在!";
    }

//    @RequestMapping("/testcvd")
//    public void testCvd() {
//        String url = "http://10.18.99.12:80/resume/api/search?keywords_type=job&keywords=java&degree=6-9&workYear=3-8&age=23-28&hTrade=2&salarys=12000-25000&hAreas=310000";
//        long l = System.currentTimeMillis();
//        for (int i=0; i<1000; i++) {
//            String forObject = restTemplate.getForObject(url, String.class);
//            System.out.println(forObject);
//        }
//        long l1 = System.currentTimeMillis();
//        System.out.println(l1-l);
//    }

    @Bean
    @Primary
    public RestTemplate restTemplate() {
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();

        //超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setSocketTimeout(3000)
                .build();
        //最大并发数
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(manager)
                .setMaxConnPerRoute(200)
                .setMaxConnTotal(200)
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
        return restTemplate;
    }

}
